package com.mls.fivedistrict.server.impl;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.mls.fivedistrict.common.ServiceResponse;
import com.mls.fivedistrict.dao.UserVoteMapper;
import com.mls.fivedistrict.entity.request.AwardRequest;
import com.mls.fivedistrict.entity.request.TransferAccountRequest;
import com.mls.fivedistrict.enums.RecordProductTypeEnum;
import com.mls.fivedistrict.enums.RecordStatusEnum;
import com.mls.fivedistrict.enums.ResponseCode;
import com.mls.fivedistrict.exception.CustomerException;
import com.mls.fivedistrict.pojo.*;
import com.mls.fivedistrict.server.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 用户投票关系表 服务实现类
 * </p>
 *
 * @author Five Team
 * @since 2018-05-15
 */
@Slf4j
@Service
public class UserVoteServiceImpl extends ServiceImpl<UserVoteMapper, UserVote> implements UserVoteService {
    @Autowired
    private SysSettingService sysSettingService;
    @Autowired
    private VoteOptionService voteOptionService;
    @Autowired
    private UserVoteOptionService userVoteOptionService;
    @Autowired
    private VoteService voteService;
    @Autowired
    private PropertyService propertyService;
    @Autowired
    private UserVoteMapper userVoteMapper;
    @Autowired
    private UserService userService;

    @Autowired
    private RecordService recordService;

    @Autowired
    private AwardService awardService;

    @Transactional
    @Override
    public boolean vote(UserVoteRequest userVoteRequest, User user) {

        //1.获取各种信息
        //获取投票
        Vote vote = voteService.selectById(userVoteRequest.getVoteId());
        if (vote.getEndDate().getTime() < System.currentTimeMillis()) {
            return false;
        }
        //检查用户投票人数是否设置
        if (vote.getPeoploTotal() > 0) {
            //检查投票人数是否超出
            if (vote.getJoinCount().compareTo(vote.getPeoploTotal()) != -1) {
                return false;
            }
        }
//        VoteOption voteOption = voteOptionService.selectById(userVoteRequest.getVoteOptionId());
        List<VoteOption> voteOptionList = voteOptionService.selectBatchIds(userVoteRequest.getVoteOptionIdList());
        if (voteOptionList == null || voteOptionList.size() == 0) {
            return false;
        }
        UserVote entity = new UserVote();
        entity.setUserId(userVoteRequest.getUserId());
        entity.setVoteId(userVoteRequest.getVoteId());
        //获取用户投票记录
        UserVote userVoteTmp = userVoteMapper.selectOne(entity);

        //获取用户的DWQ积分是否符合条件
        Property property = propertyService.getDWQDetail(userVoteRequest.getUserId());
        if (property.getTotal().compareTo(vote.getMinDwqAbility()) == -1) {
            throw new CustomerException("DWQ 积分不足,至少要拥有DWQ积分：" + vote.getMinDwqAbility());
        }
        //检查投票人是否有足够的资产能投此选项
        for (VoteOption voteOption : voteOptionList) {
            Property userVoteOptionIntegral = propertyService.getPropertyDetailByIntegral(voteOption.getIntegralId(), userVoteRequest.getUserId());
            if (userVoteOptionIntegral.getTotal().compareTo(voteOption.getPayNumber()) == -1) {
                throw new CustomerException("积分不足!");
            }
        }
        SysSetting sysSetting = sysSettingService.getSysSettingByKey("OfficialAccount");
        if (sysSetting == null || StringUtils.isEmpty(sysSetting.getSettingValue())) {
            throw new CustomerException("官方账号不存在");
        }
        User targetUser = userService.getUserByPhone(sysSetting.getSettingValue());
        if (targetUser == null) {
            throw new CustomerException("官方账号不存在");
        }

        //获取投票
        if (userVoteTmp == null) {
            UserVote userVote = new UserVote();
            userVote.setUserId(userVoteRequest.getUserId());
            userVote.setVoteId(userVoteRequest.getVoteId());
            userVote.setJoinCount(1);
            boolean insert = insert(userVote);
            if (!insert) {
                throw new CustomerException("创建用户投票出错");
            }
            for (VoteOption voteOption : voteOptionList) {
                UserVoteOption userVoteOption = new UserVoteOption();
                userVoteOption.setUserId(userVoteRequest.getUserId());
                userVoteOption.setVoteId(userVoteRequest.getVoteId());
                userVoteOption.setVoteOptionId(voteOption.getId());
                int count = userVoteOption.selectCount(
                        Condition.create().//
                                eq("user_id", userVoteRequest.getUserId()).//
                                eq("vote_id", userVoteRequest.getVoteId()).//
                                eq("vote_option_id", voteOption.getId())//
                );
                if (count + 1 > voteOption.getCanJoinTimes()) {
                    throw new CustomerException("已经超出允许投票的次数");
                }
                userVoteOption.setUserVoteId(userVote.getId());
                insert = userVoteOptionService.insert(userVoteOption);
                if (!insert) {
                    throw new CustomerException("用户投票选项更新失败");
                }
//            此处更新投票选项的投票次数
                int row = voteOptionService.addJoinCount(userVoteOption.getVoteOptionId());
                if (row <= 0) {
                    throw new CustomerException("更新投票选项次数失败");
                }
            }
//            更新投票次数,和投票的个数
            boolean add = voteService.addVoteCount(userVote.getVoteId(), vote.getVersion(), property.getTotal(), voteOptionList.size());
            if (!add) {
                throw new CustomerException("更新投票次数出错");
            }
            //此处添加为用户DWQ积分奖励
            if (vote.getRewardDwqNumber().compareTo(new BigDecimal(0)) > 0) {
                AwardRequest awardRequest = new AwardRequest();
                awardRequest.setReason("投票贡献值奖励");
                awardRequest.setSource(RecordProductTypeEnum.CONTRIBUTION.getValue());
                awardRequest.setAwardNumber(vote.getRewardDwqNumber());
                awardRequest.setIntegralId(18L);
                awardRequest.setTargetUserId(userVoteRequest.getUserId());
                awardService.awardDwq(awardRequest);
            }


            for (VoteOption voteOption : voteOptionList) {
                if (voteOption.getPayNumber().compareTo(new BigDecimal(0)) > 0) {
                    if (StringUtils.isEmpty(userVoteRequest.getWalletPassword())) {
                        throw new CustomerException("钱包密码不存在");
                    }
                    TransferAccountRequest transferAccountRequest = new TransferAccountRequest();
                    transferAccountRequest.setUserId(userVoteRequest.getUserId());
                    transferAccountRequest.setIntegralId(voteOption.getIntegralId());
                    transferAccountRequest.setTargetUserId(targetUser.getId());
                    transferAccountRequest.setWalletPassword(userVoteRequest.getWalletPassword());
                    transferAccountRequest.setValue(voteOption.getPayNumber());
                    userService.transferAsset(transferAccountRequest, RecordProductTypeEnum.VOTE.getValue());
                }
            }
            return true;
        }
        //获取投票选项
        if (userVoteTmp.getJoinCount() >= vote.getCanJoinCount()) {
            throw new CustomerException("超出投票限制");
        }
        //更新用户投票的个数
        int row = userVoteMapper.addCount(userVoteTmp.getId(), vote.getCanJoinCount());
        if (row <= 0) {
            throw new CustomerException("更新用户投票次数出错");
        }
        for (VoteOption voteOption : voteOptionList) {
            UserVoteOption userVoteOption = new UserVoteOption();
            userVoteOption.setUserId(userVoteRequest.getUserId());
            userVoteOption.setVoteId(userVoteRequest.getVoteId());
            userVoteOption.setVoteOptionId(voteOption.getId());
            userVoteOption.setUserVoteId(userVoteTmp.getId());
            int count = userVoteOption.selectCount(
                    Condition.create().//
                            eq("user_id", userVoteRequest.getUserId()).//
                            eq("vote_id", userVoteRequest.getVoteId()).//
                            eq("vote_option_id", voteOption.getId())//
            );
            if (count + 1 > voteOption.getCanJoinTimes()) {
                throw new CustomerException("已经超出允许投票的次数");
            }
            boolean insert = userVoteOptionService.insert(userVoteOption);
            if (!insert) {
                throw new CustomerException("更新用户投票选项出错");
            }

            //此处添加投票选项的投票次数
            row = voteOptionService.addJoinCount(userVoteOption.getVoteOptionId());
            if (row <= 0) {
                throw new CustomerException("添加投票选项次数出错");
            }
        }
        //此处添加投票的投票次数
        boolean add = voteService.addVoteCount(userVoteRequest.getVoteId(), vote.getVersion(), property.getTotal(), voteOptionList.size());
        if (!add) {
            throw new CustomerException("添加投票参加次数");
        }
        //此处添加为用户DWQ积分奖励
        if (vote.getRewardDwqNumber().compareTo(new BigDecimal(0)) > 0) {
            AwardRequest awardRequest = new AwardRequest();
            awardRequest.setReason("投票贡献值奖励");
            awardRequest.setSource(RecordProductTypeEnum.CONTRIBUTION.getValue());
            awardRequest.setAwardNumber(vote.getRewardDwqNumber());
            awardRequest.setIntegralId(18L);
            awardRequest.setTargetUserId(userVoteRequest.getUserId());
            awardService.awardDwq(awardRequest);
        }


        for (VoteOption voteOption : voteOptionList) {
            if (voteOption.getPayNumber().compareTo(new BigDecimal(0)) > 0) {
                if (StringUtils.isEmpty(userVoteRequest.getWalletPassword())) {
                    throw new CustomerException("钱包密码不存在");
                }
                TransferAccountRequest transferAccountRequest = new TransferAccountRequest();
                transferAccountRequest.setUserId(userVoteRequest.getUserId());
                transferAccountRequest.setIntegralId(voteOption.getIntegralId());
                transferAccountRequest.setTargetUserId(targetUser.getId());
                transferAccountRequest.setWalletPassword(userVoteRequest.getWalletPassword());
                transferAccountRequest.setValue(voteOption.getPayNumber());
                userService.transferAsset(transferAccountRequest, RecordProductTypeEnum.VOTE.getValue());
            }
        }
        return true;
    }
}
